package com.skydroid.h16

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import com.skydroid.h16.utils.String2ByteArrayUtils
import com.skydroid.h16.R
import java.io.IOException
import java.net.DatagramPacket
import java.net.DatagramSocket
import java.net.InetAddress

class SkyDataActivity: AppCompatActivity() {

    private var datagramSocket : DatagramSocket? = null

    private var receivePacket : DatagramPacket? = null

    private var mReadThread : ReadThread? = null

    @Volatile
    var isConnect = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_sky_data)
        initView()
    }

    companion object{
        fun start(context: Context){
            context.startActivity(
                Intent(context,
                    SkyDataActivity::class.java)
            )
        }
    }

    private fun initView(){
        findViewById<View>(R.id.btn_open).setOnClickListener {
            openConnect()
        }
        findViewById<View>(R.id.btn_close).setOnClickListener {
            closeConnect()
        }
        findViewById<View>(R.id.btn_send).setOnClickListener {
            sendData()
        }
    }


    /**
     * 打开连接
     */
    private fun openConnect(){
        Thread{
            try {
                datagramSocket =  DatagramSocket(14551)
                datagramSocket?.connect(InetAddress.getByName("127.0.0.1"), 14552)
            } catch (e: Exception) {
                e.printStackTrace()
            }

            var cache = ByteArray(256)
            receivePacket = DatagramPacket(cache , cache.size)

            isConnect = true

            mReadThread = ReadThread()
            mReadThread?.start()
        }.start()
    }

    /**
     * 关闭连接
     */
    private fun closeConnect(){
        isConnect = false
        //关闭读取线程
        mReadThread?.interrupt()
        mReadThread = null

        //关闭连接
        datagramSocket?.close()
        datagramSocket = null

    }

    /**
     * 发送数据
     */
    private fun sendData(){
        Thread{
            var data = "hello uart0".toByteArray()
            var packet = DatagramPacket( data, data.size)
            packet.data = data
            datagramSocket?.send(packet)
        }.start()
    }

    /**
     * 数据读取线程
     */
    inner class ReadThread:Thread(){
        override fun run() {
            try {
                while (isConnect && !isInterrupted ){
                    datagramSocket?.receive(receivePacket)
                    receivePacket?.let {
                        var tempArray = ByteArray(it.length)
                        System.arraycopy(it.data,0,tempArray,0,it.length)
                        Log.e("ReadThread","receive：${String2ByteArrayUtils.bytes2Hex(tempArray)}")
                    }
                }
            }catch (e:InterruptedException){
                e.printStackTrace()
            }catch (e: IOException){
                e.printStackTrace()
            }

        }
    }

    override fun onDestroy() {
        super.onDestroy()
        closeConnect()
    }
}